<template>
  <TodoHeader @add-todo="handleadd"></TodoHeader>
  <TodoList>
    <draggable v-model="todos" animation="300" item-key="id">
      <template #item="{ element }">
        <TodoItem
          v-bind="element"
          @toggle="handleToggle"
          @edit="handleEdit"
          @del="handleDel"
        ></TodoItem>
      </template>
    </draggable>
  </TodoList>
  <TodoFooter
    :todos="todos"
    @toggle-all="handleToggleAll"
    @clear-done="handleClearDone"
    @clear-all="handleClearAll"
  />
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import draggable from 'vuedraggable'


import TodoHeader from './components/TodoHeader.vue'
import TodoList from './components/TodoList.vue'
import TodoFooter from './components/TodoFooter.vue'
import TodoItem from './components/TodoItem.vue'
const todos = ref([])
const handleadd = (todo) => {
  todos.value.push(todo)
}
const handleToggle = (id, checked) => {
  const index = todos.value.findIndex((todo) => todo.id == id)
  todos.value[index].done = checked
}
const handleEdit = (id, content) => {
  const index = todos.value.findIndex((todo) => todo.id == id)
  todos.value[index].content = content
}
const handleDel = (id) => {
  const index = todos.value.findIndex((todo) => todo.id === id)
  todos.value.splice(index, 1)
}
const handleToggleAll = (checked) => {
  todos.value.forEach((todo) => (todo.done = checked))
}
const handleClearDone = () => {
  todos.value = todos.value.filter((todo) => !todo.done)
}
const handleClearAll = () => {
  todos.value = []
}
const getTodos = () => {
  const todoLists = JSON.parse(localStorage.getItem('todoLists') || '[]')
  todos.value = todoLists
}
watch(
  todos,
  () => {
    localStorage.setItem('todoLists', JSON.stringify(todos.value))
  },
  { deep: true }
)

onMounted(() => {
  getTodos()
})
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
}
</style>
